import router from "./index.js";
import { allMenus } from "@/grants/menu.js"


function getCRUD(id,checkedKeys) {
    let crud = "";
    const arr = ["C", "R", "U", "D"];
    arr.forEach(item => crud += (checkedKeys.includes(id + "-" + item) ? "1" : "0"));
    return crud;
}

// 过滤当前用户的路由配置

export const getCurrentUserRoutes = () => {

    // 1、获取当前用户的权限：checkedKeys
    //["1","4-1","4-2","4-3"]
    const checkedKeys = JSON.parse(sessionStorage.getItem("checkedKeys"));

    // 2、过滤：

    // const currentRoutes = allRoutes.filter(item =>checkedKeys.includes((item.id));
    const currentRoutes = [];

    allMenus.forEach(item => {
        if (!item.children) {
            if (checkedKeys.includes(item.id)) {
                currentRoutes.push({
                    path: item.path,
                    name: item.name,
                    component: item.component,
                    meta: {
                        crud:getCRUD(item.id,checkedKeys)
                    }
                });
            }
        } else {
            item.children.forEach(item => {
                if (checkedKeys.includes(item.id)) {
                    currentRoutes.push({
                        path: item.path,
                        name: item.name,
                        component: item.component,
                        meta: {
                            crud:getCRUD(item.id,checkedKeys)
                        }
                    })
                }
            })
        }
    });

    console.log("当前用户的权限数组", currentRoutes);

    // 添加对应的路由配置: addRoute;
    currentRoutes.forEach(item => {

        router.addRoute("Admin", item)

    })

    router.addRoute("Admin", {
        id: "3",
        name: "Operator",
        path: "Operator",
        component: () => import("../views/Operator/index.vue")
    })

    console.log("router.getRoutes()", router.getRoutes());

    return currentRoutes;
}

// 清除当前用户的路由配置

export const clearRoutes = () => {
    const currentRoutes = getCurrentUserRoutes();

    currentRoutes.forEach(item => {
        router.removeRoute(item.name);
    })

    console.log("清除路由后：router.getRoutes()", router.getRoutes());
}